# -!- coding: utf-8 -!-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：zipfile_model.py
#日期：2020-06-17
#备注：zipfile是python里用来做zip格式编码的压缩和解压缩的，由于是很常见的zip格式，所以这个模块使用频率也是比较高的
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import zipfile
import shutil
import os
from pycacho.cachobase.logger import Logger
logger = Logger("zipfile_model").get_log()


# zip_file-压缩文件,local_path-解压地址，name-包含文件名的文件,copy_file-文件复制并重命名
def open_file(zip_file,local_path,name,copy_file):
    try:
        if os.path.exists(zip_file):
            f = zipfile.ZipFile(zip_file)
            for file in f.namelist():
                if name in file:
                    print('解压文件相对zip文件路径名：', file)
                    f.extract(file, local_path)
                    shutil.copy(os.path.dirname(zip_file) + '/' + file, copy_file)
            f.close()
        else:
            logger.info(' >>>>>>>>查无该压缩文件%s' % zip_file)
    except:
        logger.info('>>>>>>>>>>>>压缩文件出现异常%s' % zip_file)      # 文件为空等情况


def write_file(zip_file,file,zip_name):
    zipFile = zipfile.ZipFile(zip_file,'a')              # a-附加，w-覆盖
    zipFile.write(file, zip_name,zipfile.ZIP_DEFLATED)
    print(zip_name,'压缩到：',zip_file, '成功！')
    zipFile.close()


if __name__ == '__main__':
    local_path = 'E:\zenglingwei\\file\msydloan\\'
    #zip_file = 'E:\zenglingwei\\file\msydloan\\MPLCASH_18_888190900238401_LOANCONTRACT_20191226.ZIP'
    #open_file(zip_file,local_path,'50620191130094350253216781','1.pdf')
    zip_file = 'E:\zenglingwei\\file\msydloan\\合同.zip'
    zip_name = '有签章_LW20200317HB000028_50620200317133322370873679.pdf'
    file = local_path + zip_name
    write_file(zip_file,file,zip_name)